{% extends "baseD.html" %}

{% block headtitle %}- View Scene{% endblock %}

{% block css %}
	<link href="/live3dstatic/css/viewScene.css" rel="stylesheet" type="text/css" media="screen" />
{% endblock %}

{% block scripts %}
	<script type="text/javascript" src="/live3dstatic/scripts/site.js"></script>
	<script type="text/javascript" src="/live3dstatic/scripts/helperFunctions.js"></script>
	<script type="text/javascript" src="/live3dstatic/scripts/earth.js"></script>
	<script type="text/javascript" src="/live3dstatic/scripts/viewScene.js"></script>
	<script type="text/javascript" src="/live3dstatic/scripts/amos.js"></script>
	<script type="text/javascript" src="/live3dstatic/scripts/canvas.js"></script>
	<script type="text/javascript" src="/live3dstatic/scripts/matrix.js"></script>
	<script type="text/javascript" src="/live3dstatic/scripts/calibration.js"></script>
	
	<script type="text/javascript">
		/* 
			This is really messy and I apologize. I inherited messy and added
			messy to messy making it messier.
		*/

		window.onresize = buildWindowResize;

		// close any active menus when the user clicks away
		document.onclick = function() {
    		if ( !menuActive && menuOpen != 'none' ) {
    			closeActiveMenu();
    			prevMenuOpen = 'none';
    		}
    	}

    	// keep the two side-by-side windows at a height that is
    	// viewable without needing to scroll
		function buildWindowResize() {
			var windowHeight = window.innerHeight;
			var geHeight = windowHeight - 210;
			
			document.getElementById('map3d').style.height = geHeight + "px";
		}

		// embed popup for already calibrated scenes
		function openEmbedCode() {
			document.getElementById('embedOverlay').style.display = "block";
			document.getElementById('embedLightbox').style.display = "block";
			document.getElementById('map3d').style.visibility = 'hidden';
		}
		function closeEmbedCode() {
			document.getElementById('embedOverlay').style.display = "none";
			document.getElementById('embedLightbox').style.display = "none";
			document.getElementById('map3d').style.visibility = 'visible';
		}

		// user not logged in, toggles display of message (on mouseover)
		// that they can log in a rate the scene
		function toggleRatingMessage() {
			var stars = document.getElementById('stars');
			var notLogged = document.getElementById('notLogged');

			if ( notLogged.style.display == "none" ) {
				notLogged.style.display = "block";
				stars.style.display = "none";
			} else {
				notLogged.style.display = "none";
				stars.style.display = "block";
			}
		} 

		// user logged in, toggles display of message (on mouseover) 
		// for voting or "already voted"
		function toggleRatedMessage() {
			var stars = document.getElementById('stars');
			var alreadyVoted = document.getElementById('alreadyVoted');

			if ( alreadyVoted.style.display == "none" ) {
				alreadyVoted.style.display = "block";
				stars.style.display = "none";
			} else {
				alreadyVoted.style.display = "none";
				stars.style.display = "block";
			}
		} 

		// highlights one, two, ..., five stars
		// called on mouseover
		var rating_order = ["off","off","off","off","off"];
		function highlightRating(num) {
			for ( var i = 1; i <= num; i++ ) {
				document.getElementById("star_"+i).className = "star_vote";
			}
		}
		function resetRating() {
			for ( var i = 1; i <= 5; i++ ) {
				document.getElementById("star_"+i).className = "star_"+rating_order[i-1];
			}
		}

		// navigation menus
		// functions allow dropdown menus to open and close on click
		// active and open menu vars ensure menus don't close once opened and
		// clicked inside of
		var menuActive = false;
		var menuOpen = 'none', prevMenuOpen = 'none', buttonOpen = 'none';
		function openMenu(menuID, buttonID) {
			if ( menuID == prevMenuOpen ) {
				prevMenuOpen = 'none';
			} else {
				document.getElementById(menuID).style.display = "block";
				toggleActiveButton(buttonID);
				menuOpen = menuID;
				buttonOpen = buttonID;

				if ( menuID == 'sceneSettingsDropdown' || menuID == 'polygonsDropdown' ) { 	
					var shim = ( menuID == 'sceneSettingsDropdown' ) ? document.getElementById('iframeShimSceneSettings') : document.getElementById('iframeShimPolySettings');
					var menu = document.getElementById(menuID);

					shim.style.display = 'block';
					shim.style.width = menu.offsetWidth + 'px';
					shim.style.height = menu.offsetHeight + 'px';
				}
			}
		}
		function closeActiveMenu() {
			if ( menuOpen != 'none' ) {
				document.getElementById(menuOpen).style.display = "none";
				toggleActiveButton(buttonOpen);

				if ( menuOpen == 'sceneSettingsDropdown' || menuOpen == 'polygonsDropdown' ) {
					document.getElementById('iframeShimSceneSettings').style.display = 'none';
					document.getElementById('iframeShimPolySettings').style.display = 'none';
				}
				
				prevMenuOpen = menuOpen;
				menuOpen = 'none';
			}
		}
		function toggleActiveMenu(bool) {
			menuActive = bool;
		}
		function toggleActiveButton(buttonID) {
			var buttonObj = document.getElementById(buttonID);

			if ( buttonObj.style.backgroundPosition == '50% -31px' || buttonObj.style.backgroundPosition == 'center -31px' ) {
				buttonObj.style.borderColor = '#CCCCCC';
				buttonObj.style.backgroundPosition = 'center 0px';
				buttonObj.style.color = "#b5b5b5";
			} else {
				buttonObj.style.borderColor = '#777777';
				buttonObj.style.backgroundPosition = 'center -31px';
				buttonObj.style.color = "#777777";
			}
		}

		// animated wheel shows when the image is loading
		function imageLoaded() { 
			document.getElementById('loadingImage').style.display = 'none';
			document.getElementById('failedImage').style.display = 'none';
			document.getElementById('smallimage').style.display = 'block';
		}
		function imageFailedToLoad() { 
			document.getElementById('loadingImage').style.display = 'none';
			document.getElementById('failedImage').style.display = 'block';
			document.getElementById('smallimage').style.display = 'none';
		}

		var viewScene;
		var viewLoading;
		var amos = null;
		{% if calibration %}
			var calib;
			function initCalibration() {
				var M = new Matrix(4,3, [[{{calibration.m11}}, {{calibration.m12}}, {{calibration.m13}}, {{calibration.m14}}], 
							 [{{calibration.m21}}, {{calibration.m22}}, {{calibration.m23}}, {{calibration.m24}}],
							 [{{calibration.m31}}, {{calibration.m32}}, {{calibration.m33}}, {{calibration.m34}}]]
						);
				var camCenter = {x: {{calibration.cameraX}}, y: {{calibration.cameraY}}, z: {{calibration.cameraZ}},
								lat: {{scene.cameraLatitude}}, lon: {{scene.cameraLongitude}}, alt: {{scene.cameraAltitude}}};
				var pitch = {{scene.cameraTilt}};
				var heading = {{scene.cameraHeading}};
				var origin = {lat: {{calibration.originLatitude}}, lon: {{calibration.originLongitude}}, alt: {{calibration.originAltitude}} };
				var width = {{scene.width}};
				var height = {{scene.height}};
				calib = new Calibration(M, camCenter, pitch, heading, origin, width, height)
			}
		{% endif %}
		
		// initializes the viewing of the 3d scene
		// sets up the image refresher, flies google earth to correct
		// location and camera pitch, etc.
		function init3D() {
			viewScene = new ViewScene('{{scene.url}}', {{scene.index}})
			viewLoading = new LoadingOverlay()
			
			// add AMOS functionality.
			{% if scene.amosId %}
				viewScene.initAMOS({{scene.amosId}});
			{% endif %}
			
			// add all the models.
			{% for mesh in meshes %}
				viewScene.addModel({{mesh.index}}, {{mesh.originLatitude}}, {{mesh.originLongitude}}, {{mesh.originAltitude}});
			{% endfor %}
			
			viewScene.makeRefresher();
			setInterval('viewScene.refreshImage()', 1000);
			
			//****** This puts the view up correctly ********
			{% if scene.calibrated %}
				initJumpToFull({{scene.cameraLatitude}}, {{scene.cameraLongitude}}, {{scene.cameraAltitude}}, {{scene.cameraRoll}}, {{scene.cameraTilt}}, {{scene.cameraHeading}});
			{% else %}
				jumpTo( {{scene.cameraLatitude}}, {{scene.cameraLongitude}} );	
			{% endif %}
			
			{% if calibration %}
				initCalibration();
			{% endif %}
		}

		// selects text inside the code holder
		// I inherited this, seems like it's for the embed menu
		function selectText() {
			if (document.selection) {
				var range = document.body.createTextRange();
				range.moveToElementText(document.getElementById('codeHolder'));
				range.select();
			}
			else if (window.getSelection) {
				var range = document.createRange();
				range.selectNode(document.getElementById('codeHolder'));
				window.getSelection().addRange(range);
			}
		}

	</script>
{% endblock %}

{% block onload %}googleInit(){% endblock %}

{% block divtitle %}- View Scene{% endblock %}

{% block content %}
	<div id="embedLightbox">
		<img onclick="closeEmbedCode();" src="../live3dstatic/images/close_button.png" id="closeButton" />
		<div id="codeHolder" onclick="selectText()">
			&lt;iframe src="http://www.projectlive3d.com/embed?scene={{scene.index}}&h=400" frameborder="0" width="450" height="620"&gt; &lt;/iframe&gt;
		</div>
	</div>
	<div id="embedOverlay"></div>

	<div id="page">
		<div id="leftside">
			<div id="imageButtonWrapper">
				<div id="imageSettingsButton" title="Image Settings" onmouseover="toggleActiveMenu(true)" onmouseout="toggleActiveMenu(false)" onclick="closeActiveMenu();openMenu('imageSettingsDropdown',this.id);"></div> 
				<div id="imageSettingsDropdown" onmouseover="toggleActiveMenu(true)" onmouseout="toggleActiveMenu(false)">
					<h3>Texture</h3>
					<form id='textureForm' style="margin:5px 0px 0px 20px;">
						<input style="margin-left:5px;cursor:pointer;" type="radio" name='textureOptions' id="currentImage" value='current' onchange="viewScene.changeTexture()" checked />
						<label for="currentImage">Current</label>
						
						{% ifnotequal scene.firstImage  "-1" %}
							<input style="margin-left:5px;cursor:pointer;" type="radio" name='textureOptions' id="defaultImage" value='original' onchange="viewScene.changeTexture()" />
							<label for='defaultImage'>Original</label>
						{% endifnotequal %}
						
						{% if scene.amosId %}
							<input style="margin-left:5px;cursor:pointer;" type="radio" name='textureOptions' id="timeLapse" value='timelapse' onchange="viewScene.changeTexture()" />
							<label for="timeLapse">Time Lapse</label>
						{% endif %}

						{% if scene.amosId %}
							<div id="timelapse_control">
								<p style="text-align:center;">
									<input type='button'  style="cursor:pointer" onclick="viewScene.amos.prevYear();" value="Previous Year" />
									<span id="currYear"></span>
									<input type='button' style="cursor:pointer"  onclick="viewScene.amos.nextYear();" value="Next Year" />
								</p>
								<center><img src='' id='ImageBrowser' width='330' height='50' onclick='viewScene.amosClick(event)'></center>
							</div>
						{% endif %}
					</form>
	
					{% if scene.is_private %} <!-- scene.is_private -->
						<br />
						<h3>Scene options</h3>
						<div style="margin-left: 25px;">
							Your scene is currently visible only to you.<br />
							<form style="float:left;margin-top:5px;" action='makePublic' method='post' >
								<input type='hidden' name='scene' value='{{scene.index}}'>
								<input type='submit' style="cursor:pointer;" value='Make Scene Public'>
							</form>
							<form style="float:left;margin:5px 0 0 5px;" action='adminModify' method='post' onsubmit="return confirm('Are you sure you want to delete the entire scene?  This is irreversible.');">
								<input type='hidden' name='scene' value='{{scene.index}}'>
								<input type='hidden' name='deleteScene' value='yes'>
								<input type='hidden' name='redirTo' value='viewAll'>
								<input type='submit' style="cursor:pointer;" value='Delete Scene'>
							</form>
						</div>
						<div style="clear:both;"></div>
					{% endif %}

					{% if admin %} <!-- admin -->
						<br />
						<h3>Admin control</h3>
						<form action='adminModify' method='post' onsubmit="return confirm('Are you sure you want to delete the entire scene? This is irreversible.');" style="margin:5px 0 0 25px;">
							<input type='hidden' name='scene' value='{{scene.index}}'>
							<input type='hidden' name='deleteScene' value='yes'>
							<input type='submit' style="cursor:pointer;" value='Delete Scene'>
						</form>
					{% endif %}
				</div>

				<div id="addPointsButton" title="Add/Modify Points" onmouseover="toggleActiveMenu(true)" onmouseout="toggleActiveMenu(false)" onclick="closeActiveMenu();openMenu('addPointsDropdown',this.id);"></div> 
				<div id="addPointsDropdown" onmouseover="toggleActiveMenu(true)" onmouseout="toggleActiveMenu(false)">
					<h3>Add/Modify Points</h3>
					<input type="button" style="cursor:pointer;margin:20px 0 0 5px;float:left;" value="Add Points to Scene" onclick="viewLoading.display('Loading...', 'We\'re retrieving your scene. This could take a few seconds.'); parent.location='build?scene={{ scene.index }}';" />
					<img src="/live3dstatic/images/or.png" height="70" style="float:left;margin:0 10px;" />
					<input type="button" style="cursor:pointer;margin:20px 0 0 0;float:left;" value="Modify Points in Scene" onclick="parent.location='modifyScene?scene={{ scene.index }}'" />
				</div>
			</div>

			<div id="imageContainer">
				<div class="group">
					<span id="viewingTitle">
						Viewing 
						{% if scene.name %}
							({{scene.name}})
						{% else %}
							(Scene)
						{% endif %}
					</span>

					{% if credit %}
						<span id="from_text">From <a href="{{credit}}">{{credit}}</a></span>
					{% endif %}

					{% if scene.amosId %}
						AMOS information: <a href="http://amosweb.cse.wustl.edu/camera?id={{scene.amosId}}"> Camera {{scene.amosId}}</a><br/>
					{% endif %}

					<img id="loadingImage" src="/live3dstatic/images/loading.gif" />
					<img id="smallimage" src="{{ scene.url }}" onload="imageLoaded();" onerror="imageFailedToLoad();" />
					<img id="failedImage" src="/live3dstatic/images/failedImage.gif" />

					<p id="datetime"></p>
					 
					 <div 
						{% if not username %}
							onmouseover="toggleRatingMessage()" onmouseout="toggleRatingMessage()"
						{% else %}
							{% if not votable %}onmouseover="toggleRatedMessage()" onmouseout="toggleRatedMessage()"{% endif %}
						{% endif %}
					>
					
						<div id="stars" onmouseout="resetRating()">
							{% for i in stars %}
								<div id="star_{{forloop.counter}}" onclick="parent.location='rate?scene={{scene.index}}&amp;rating={{forloop.counter}}'" onmouseover="highlightRating({{forloop.counter}});" class="{%if i %}star_on{%else%}star_off{%endif%}"></div>
								<script type="text/javascript">rating_order[{{forloop.counter}}-1] = {% if i %}"on"{% else %}"off"{% endif %}</script>
							{% endfor %}
						</div>
						<div style="clear:both;"></div>
						<div id="alreadyVoted" style="height:26px;line-height:26px;display:none;">You have already rated this scene!</div>
						<div id="notLogged" style="height:26px;line-height:26px;display:none;"><a href="{{logInURL}}">Log in</a> to rate a scene.</div>
					</div>
					<br/>
					{% if scene.ratingAverage %}
						<div style="padding-bottom:10px;">Rating: {{scene.ratingAverage|floatformat}} out of 5</div>
					{% else %}
						<div style="padding-bottom:10px;">This scene has not been rated.</div>
					{% endif %}
				</div>
			</div>
		</div>

		<div id="rightside">
			<div id="sceneButtonWrapper">
				<iframe id="iframeShimSceneSettings" border="0" scrolling="no"></iframe>
				<iframe id="iframeShimPolySettings" border="0" scrolling="no"></iframe>
				<div id="sceneSettingsButton" title="Map Settings" onmouseover="toggleActiveMenu(true)" onmouseout="toggleActiveMenu(false)" onclick="closeActiveMenu();openMenu('sceneSettingsDropdown',this.id);"></div> 
				<div id="sceneSettingsDropdown" onmouseover="toggleActiveMenu(true)" onmouseout="toggleActiveMenu(false)">
					<h3>View options</h3>
					<div style="margin:5px 0 0 20px;">
						{% if scene %}
							{% if scene.calibrated %}
								<input type='button' style="margin-right:10px;cursor:pointer;" value="Reset View" 
							    onclick="jumpToFull({{scene.cameraLatitude}}, {{scene.cameraLongitude}}, {{scene.cameraAltitude}},{{scene.cameraRoll}}, {{scene.cameraTilt}}, {{scene.cameraHeading}});" />
							{% else %}
								<input type='button' style="margin-right:10px;cursor:pointer;" onclick="jumpTo( {{scene.cameraLatitude}}, {{scene.cameraLongitude}} );" value ="Reset View" />
							{% endif %}
						{% endif %}
						<input type="button" style="padding:5px;cursor:pointer;" value="Export to KML" onclick="parent.location='toKMZ?scene={{ scene.index }}'">
						<input id='embedButton' type='button' style="padding:5px;cursor:pointer" onclick="openEmbedCode();" value='Embed into another site'>
					</div>
					<br />
					<form name="visualize">
						<span class="h3">Show structures</span><br />	
						<div style="margin:5px 0 0 20px;">				
							<input type="checkbox" onchange="toggleBuildings();" id="showBuildings" checked style="margin:3px;cursor:pointer;"/>
							<label for="showBuildings">  Buildings </label>
							<input type="checkbox" onchange="toggleGrayBuildings();" id="showGrayBuildings" checked style="cursor:pointer; margin:3px; margin-left:10px; "/>
							<label for="showGrayBuildings">  Gray buildings </label>
						</div>
						<br />
						<span class="h3">Change altitude </span>
						<div style="margin:5px 0 0 20px;">	
			                <input type="text" id="spee" class="inp1" value="100" size="5" style="margin:3px;" onfocus="this.select();" />
			                <input type="button" onclick="javascript:changeSpeed();javascript:changeAlt('decrease')" style="cursor:pointer;margin:3px;" value=" up " />
			                <input type="button"  onclick="javascript:changeSpeed();javascript:changeAlt('increase')" value=" down " style="cursor:pointer;" />
			            </div>
					</form><!-- End visualize form -->
					{% if scene.calibrated %}<!-- scene.calibrated -->
						<br />
						<h3>Camera frustum</h3>
						<div style="margin:5px 0 0 20px;" id="viewFrust">
		                    <label for="">View frustum: </label>
		                    <input type="checkbox" id="frustumBox" style="cursor:pointer;" onchange="calib.toggleFrustum()"/>
		                    <label for="edgeLength" style="margin-left:10px;">Length (meters): </label>
		                    <input type="text" id="edgeLength" value="50" size="2" onfocus="this.select();" onchange="calib.updateFrustum()">
		       			</div><!-- end viewFrust -->
		       		{% endif %}
				</div>
				{% if meshes %}
					<div id="polygonsButton" title="Polygons" onmouseover="toggleActiveMenu(true)" onmouseout="toggleActiveMenu(false)" onclick="closeActiveMenu();openMenu('polygonsDropdown',this.id);"></div> 
					<div id="polygonsDropdown" onmouseover="toggleActiveMenu(true)" onmouseout="toggleActiveMenu(false)">
						<h3>Show/hide polygons</h3>
						<input type='button' style="padding:5px;margin:10px;cursor:pointer;" onclick="viewScene.selectAll();" value="Select all" />
						<input type='button'  style="padding:5px;margin:10px;cursor:pointer" onclick="viewScene.unselectAll();" value="Deselect all" />
						<form id="checkBoxForm" >
							<div id="checkBoxTable" >
								{% for mesh in meshes %}
									<span class="checkBoxLabel" >	
										<input type="checkbox" style="margin-left: 10px;" name="checkList" id="mesh{{ mesh.index }}" onchange="viewScene.toggleModel({{mesh.index}});">
										<label for="mesh{{ mesh.index }}" > {{ mesh.name }}</label>
									</span>
								{% endfor %}
							</div>
						</form>
					</div>
				{% endif %}
			</div>

			<div id="gecontainer">
				<div id="map3d"></div>
			</div>
		</div>

		<div style="clear:both;"></div>
	</div>

	<script type="text/javascript">buildWindowResize();</script>
{% endblock %}
		
{% block scripts2 %} {% endblock %}
